package com.goods.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goods.dao.StbMapper;
import com.goods.pojo.IptvUserBean;
import com.goods.pojo.StbBean;
import com.goods.service.IIptvUserService;
import com.goods.service.IStbService;
import com.goods.util.CommonTools;
import com.somtacode.core.base.result.ResponseDataResult;

@Service
public class StbServicelmpl implements IStbService{
	
	@Autowired
	private StbMapper stbMapper;

	@Autowired
	private IIptvUserService iptvUserService;
	
	/**
	 * 新增机顶盒(根据userid进行区分，如果有进行修改，没有进行新增)
	 */
	@Override
	public ResponseDataResult addStb(StbBean stb,String userid,Integer cpspid) {
		try {
			List<IptvUserBean> list = iptvUserService.getIptvUserByUser(userid,cpspid); 
			if (!CommonTools.isNullOrEmpty(list)) { 
				stb.setStbid(list.get(0).getSmpStbid());
				stb.setMacaddress(list.get(0).getMacaddress());
				stb.setDeviceType(list.get(0).getDeviceType());
				stb.setRebootStatus(list.get(0).getRebootStatus());
				stb.setRebootLastTime(list.get(0).getRebootLasttime()); 
				stb.setUploadlogStatus(list.get(0).getUploadlogStatus());
				stb.setUploadlogLastTime(list.get(0).getUploadlogLasttime());
				stbMapper.updateStb(stb);
			}else {  
				stbMapper.addStb(stb);
				List<IptvUserBean> addlist = iptvUserService.getIptvUserByUser(userid,cpspid);
				if (CommonTools.isNullOrEmpty(addlist)) {
					IptvUserBean iub = new IptvUserBean();
					iub.setSmpStbid(stb.getStbid());
					iub.setUserid(userid);
					iub.setPassword("123456");
					iub.setCpspid(cpspid);
					iub.setAccountType(0);
					iptvUserService.addIptvUser(iub);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return ResponseDataResult.setResponseResult();
	}

	/**
	 * 删除机顶盒(根据userid进行区分，如果有进行删除，没有不删除)
	 */
	@Override
	public ResponseDataResult deleteStb(String userid,Integer cpspid) {
		List<IptvUserBean> deleteList = iptvUserService.getIptvUserByUser(userid,cpspid);
		if (!CommonTools.isNullOrEmpty(deleteList)) {
				stbMapper.deleteStb(deleteList.get(0).getSmpStbid());
				iptvUserService.deleteIptvUserStbid(userid,cpspid);
		}else{
			System.out.println("删除的userid存在");
		}
		return ResponseDataResult.setResponseResult();
	}

	@Override
	public ResponseDataResult updateStb(StbBean stb,String userid) {
		stbMapper.updateStb(stb);
		return ResponseDataResult.setResponseResult();
	}

	@Override
	public List<StbBean> getStb(String id) {
		return stbMapper.getStb(id);
	}

	@Override
	public PageInfo<StbBean> listStb(Integer pageNum, Integer pageSize, StbBean stb) {
		Page<StbBean> page = PageHelper.startPage(pageNum,pageSize);
		this.stbMapper.listStb(stb);
		return page.toPageInfo();
	}
}
